package com.huawei.esdk.platform.professional.local.impl.utils;

import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.log4j.Logger;

import com.huawei.esdk.tp.professional.local.impl.utils.Base64Utils;

public class RSA2048Utils
{
    private static final Logger LOGGER = Logger.getLogger(RSA2048Utils.class);
    
    public static final String ALGORITHM = "RSA";
    
    private static String RSA_TRANSFORMATION = "RSA/ECB/OAEPWithSHA-512AndMGF1Padding";
    
    private static String key =
        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg+hWYDxV893YYcDdBAF4iHR9e3iojCMAp+RBuH5IrUkS95CUbeqqOSoiba6KsFiu+5qRS+N7ZQgLcXo0Bz8wEHN3MDDzOrJt5Jc65Nd8wwqGfZciQvrR8NR9cj1VZfZimz19duZJA3rOAb0mw9KTPIoFbGOTuWcHNk7331O5sedjoxX/VpVhs7TTBBSYfVq4c0RY+iDzksWQ6iaV1dMxcqwK2/vQzTycHu1uZoPCAo7nZegXwNRjOKzhjPZsro+/BNEdmxIAXvqrV7HzG7WH3dWVhO6NGAiHWgbuFBRiMLawjWFNJ9XXqvMFXju0hv8Mb/YWTe2mUV6Kp57OQR2NQwIDAQAB";
    
    public static byte[] encode(byte[] data)
        throws Exception
    {
        // 对公钥解密
        byte[] keyBytes = Base64Utils.getFromBASE64(key);
        
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        
        // 对数据加密
        Cipher cipher = Cipher.getInstance(RSA_TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        
        return cipher.doFinal(data);
    }
    
    public static byte[] decode(byte[] data)
        throws Exception
    {
        
        // 对公钥解密
        byte[] keyBytes = Base64Utils.getFromBASE64(key);
        
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        
        // 对数据加密
        Cipher cipher = Cipher.getInstance(RSA_TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        
        return cipher.doFinal(data);
    }
    
    public static String decodeFromBase64(String password)
    {
        try
        {
            return new String(RSA2048Utils.decode(Base64Utils.getFromBASE64(password)), "UTF-8");
        }
        catch (Exception e)
        {
            LOGGER.error("password decode error", e);
            return "";
        }
    }
    
    public static void setPublicKey(String key)
    {
        RSA2048Utils.key = key;
    }
}
